package com.define.commons.demo.controller;

import com.define.commons.common.base.BaseController;
import com.define.commons.common.utils.RS;
import com.define.commons.demo.domain.Student;
import com.define.commons.demo.domain.Teacher;
import com.define.commons.demo.service.StudentService;
import com.gitee.fastmybatis.core.query.Query;
import com.gitee.fastmybatis.core.query.param.PageParam;
import com.gitee.fastmybatis.core.query.param.SortParam;
import com.gitee.fastmybatis.core.util.MyBeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Demo Controller
 * @Author xiewenlong
 * @Date 2018/11/14 16:08
 */
@Slf4j
@RestController
@RequestMapping("/student")
public class StudentController extends BaseController {

    @Autowired
    private StudentService studentService;

    /*
     * 分页 实体类作为参数 和分页信息 排序信息
     */
    @GetMapping
    RS page(Student bean, PageParam pageParam, SortParam sortParam){
        Query query = Query.build(bean).addPaginationInfo(pageParam).addSortInfo(sortParam);
        return new RS(studentService.page(query));
    }

    /*
     * 根据id获取一条记录
     */
    @GetMapping("{id}")
    RS get(@NotNull @PathVariable Long id){
        return new RS(studentService.getById(id));
    }

    /**
     * 添加一条记录
     */
    @PostMapping
    RS add(@NotNull Student bean){
        studentService.save(bean);
        return RS.ok();
    }

    /**
     * 修改一条记录
     */
    @PutMapping
    RS edit(@NotNull Student bean){
        Assert.isNull(bean.getId(), "id is null!");
        studentService.update(bean);
        return RS.ok();
    }

    /**
     * 删除一条记录
     */
    @DeleteMapping("{id}")
    RS del(@NotNull @PathVariable Long id){
        studentService.deleteById(id);
        return RS.ok();
    }

    /*
     * 连表查询返回指定字段转换为其他实体类型
     */
    @GetMapping("join")
    RS join(){
        Query query = new Query();
        query.join("left join teacher t2 on t.teacher_id = t2.id");
        List<String> columns = Arrays.asList(" t2.name as name ", " t2.id as id ");
        List<Map<String, Object>> maps = studentService.listMap(columns, query);
        List<Teacher> teachers = MyBeanUtil.mapListToObjList(maps, Teacher.class);
        return new RS(teachers);
    }

    /**
     * 一对一
     */
    @GetMapping("full")
    RS full(){
        Student student = studentService.full();
        System.out.println(student);
        System.out.println(student.getTeacher());
        return new RS(student);
    }
}
